// const Chapter = require('../model/chapter.model')
// const Course = require('../model/courses.model')
// const Video = require('../model/video.model')

const {
  edu_chapters: Chapter,
  edu_courses: Course,
  edu_videos: Video
} = require('../dbModel/index')

class coursesService {
  //保存课程信息方法
  async saveCourseInfoSer(courseInfo) {
    const res = Course.create(courseInfo)
    return (await res).dataValues
  }

  //查找所有课程信息方法
  async findAllCourses(pageNum, pageSize) {
    // //1.获取总数
    // const count = await Course.count()
    // //2.获取分页具体数据
    // const offset = (pageNum-1).pageSize
    // const rows = await Course.findAll({offset:offset,limit:pageSize*1})

    //优化
    const offset = (pageNum - 1) * pageSize
    //
    const { count, rows } = await Course.findAndCountAll({
      offset: offset,
      limit: pageSize * 1,
      order: [['id', 'DESC']]
    })
    return {
      pageNum,
      pageSize,
      total: count,
      list: rows
    }
  }

  //通过ID查找单门课程信息
  async findCourseInfoById(id) {
    const res = await Course.findByPk(id, {
      attributes: ['title', 'lesson_num']
    })

    return res.dataValues
  }

  //查找所有章节信息
  async findAllChapter() {
    const res = await Chapter.findAll({ attributes: ['course_id', 'title'] })
    return res
  }

  //通过课程ID查找所有章节和课时信息
  async findChAndLeByCourseId(courseId) {
    const res = await Chapter.findAll({
      where: {
        course_id: courseId
      },
      include: [
        {
          model: Video,
          as: 'lessonInfo'
        }
      ]
    })
    return res
  }

  //通过ID获取章节信息
  async findChapterById(id) {
    const res = await Chapter.findByPk(id, {
      attributes: ['id', 'course_id', 'chapterName', 'description', 'sort']
    })

    return res
  }

  // async updateById({ id, username, password, is_admin }) {
  //   const whereOpt = { id }
  //   const newUser = {}

  //   username && Object.assign(newUser, { username })
  //   password && Object.assign(newUser, { password })
  //   is_admin && Object.assign(newUser, { is_admin })

  //   console.log(newUser, 'newUser')
  //   const res = await User.update(newUser, { where: whereOpt })

  //   return res[0] > 0 ? true : false
  // }
  async updateChapter(courseInfo) {
    const { id } = courseInfo
    if (id) {
      const res = await Chapter.update(courseInfo, { where: { id } })
      return res[0] > 0 ? true : false
    } else {
      const res = await Chapter.create(courseInfo)
      return res
    }
  }

  //关联模型测试
  async testSer() {
    const res = await Course.findAll({
      include: [
        {
          model: Chapter,
          as: 'chapterDetail'
        }
      ]
    })

    return res
  }
}

module.exports = new coursesService()
